<template>
    <div class="pjt-mt-add-view">

      <modules-title class="title-position" :titleName="title">

        <template slot="btn">
          <el-button
            plain
            size="mini"
            @click="goBack">返回</el-button>

          <el-button
            v-if="!datas.status"
            type="primary"
            size="mini"
            @click="confirmClick">提交</el-button>


          <template v-if="isPerson">
            <el-button
              v-if="datas.status == 4 || datas.status == 52"
              type="primary"
              size="mini"
              @click="saveClick">保存</el-button>
            <el-button
              v-if="datas.status == 4 || datas.status == 52"
              type="primary"
              size="mini"
              @click="auditProject">提交审批</el-button>

          </template>

        </template>

      </modules-title>

      <div class="pj-content">


        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="first">
            <information-view ref="infomation" @modelChange="modelChange"></information-view>
          </el-tab-pane>
          <el-tab-pane label="项目成员" name="second" v-if="datas.status > 3">
            <members :datas="clinical_content_top" :members="clinical_content_top.member" @refreshMember="refreshMember" @deleteMember="deleteMember"></members>
          </el-tab-pane>
          <el-tab-pane label="项目任务" name="third" v-if="datas.status > 3">
            <plan-view ref="planList" :datas="clinical_content_top" :documents="documents" @save-change="automaticSave"></plan-view>
          </el-tab-pane>

        </el-tabs>

      </div>

      <plan-book-edit-view ref="planBookView" @confirmDataBack="confirmDataBack"></plan-book-edit-view>


    </div>
</template>

<script>
  import planBookEditView from "./modules/planBookEditView";
  import informationView from './modules/informationView'
  import members from "./modules/members";
  import planView from "./modules/planView";
  import documentView from "./modules/documentView";

    export default {
        name: "index",
        components:{informationView,members,planView,documentView,planBookEditView},
        data:function () {
            return{
                activeName:'first',
                documents:{
                    id:1,
                    list:[]
                },
                datas:{
                    project_design_book:{},
                },
                clinical_content_top:{
                    member:[],
                    project_task:[],
                    project_document:[],
                    project_problem:[],
                    project_transaction:[],
                    plan_start_time:'',
                    plan_end_time:'',
                    project_duration:0,
                    project_template_id:'',
                    project_template_name:'',
                    member_id:[],
                },
                isFirst:true,
                title:'项目新增',
                isPerson:false,
            }
        },
        created:function(){
            if (this.$route.query.id){
                this.getData(this.$route.query.id)
                this.title = "项目编辑"
            }else{
                this.title = "项目新增"
            }
        },
        mounted:function() {


        },
        methods: {
            checkPerson:function(){
                if (this.datas.project_person_in_charge_id == this.$store.getters.userInfo.user.id){
                    this.isPerson = true
                }else{
                    this.isPerson = false
                }

            },
            refreshMember:function(data){
                if (this.$refs.planList){
                    console.log(data)
                    this.$refs.planList.changeMember(data)
                }
            },
            deleteMember:function(data){
                if (this.$refs.planList){
                    this.$refs.planList.deleteMember(data)
                }
            },
            getData:function(id){
                this.$api.PROJECT_MANAGER_PROJECT_DETAIL(id).then(res=>{
                    if (res.code == 200){
                        this.activeName = 'second'
                        this.isFirst = true;
                        this.datas = res.data;
                        this.checkPerson()
                        if (this.$refs.infomation){
                            this.$refs.infomation.setData(res.data)
                        }

                        if (this.datas){
                            this.clinical_content_top = this.datas

                            if (this.clinical_content_top.member){
                                this.clinical_content_top.member.forEach(item=>{
                                    item.name = item.member_name
                                    item.roles = item.project_roles
                                })
                            }else {
                                this.clinical_content_top.member = [];
                                this.clinical_content_top.member_id = [];
                            }
                        }

                        setTimeout(()=>{
                            if (this.$refs.planList && this.datas){
                                this.$refs.planList.setData(this.datas)
                            }
                        },500)
                    }
                }).catch(err=>{

                })
            },
            goBack:function () {
                this.$router.back();
            },
            handleClick:function () {
                if (this.activeName == "third" && this.isFirst){
                    this.isFirst = false;
                    if (this.$refs.planList && this.datas){
                        this.$refs.planList.setData(this.datas)
                    }
                }
            },
            delectDoc:function (doc) {
                if (this.$refs.planList){
                    this.$refs.planList.deleteDoc(doc)
                }
            },
            addDoc:function (doc) {
                if (this.$refs.planList){
                    this.$refs.planList.addDoc(doc)
                }
            },
            modelChange:function (id) {
                if (this.$refs.planList){
                    this.$refs.planList.getData()
                }
            },
            confirmClick:function () {
                if (this.$refs.infomation){
                    //let data = this.$refs.infomation.checkForm()
                    // this.$refs.infomation.checkForm((valid)=>{
                    //     if (valid){
                    //         let data = this.$refs.infomation.formData
                    //
                    //         console.log(data);
                    //         this.dealData(data);
                    //     }
                    // })
                    if (this.$refs.infomation.checkForm()){
                        let data = this.$refs.infomation.formData

                        console.log(data);
                        this.dealData(data);

                        this.$api.PROJECT_MANAGER_PROJECT_CREATE(this.datas).then(res=>{
                            if (res.code == 200){
                                this.$route.params.refresh = true;
                                this.$router.back();

                            }else{
                                this.$message.error(res.msg)
                            }
                        }).catch(err=>{

                        })
                    }else{

                    }
                }
            },
            dealData:function (data) {
                this.datas = data;
            },
            confirmPlanBook:function () {
                if (this.$refs.planBookView){
                    this.$refs.planBookView.openDialog();
                }
            },
            createMeeting:function(id){
                console.log("暂无此功能")
            },
            planBookCheck:function(){
                this.$api.PROJECT_MANAGER_PROJECT_STATUS(this.datas.id,3).then(res=>{
                    if (res.code == 200){
                        this.$message.success("成功")
                        // this.getData(this.datas.id)
                        this.$router.back()
                    }
                }).catch(err=>{

                })
            },
            async auditProject(){

                if (this.$refs.planList){
                    let list = this.initOldData(this.$refs.planList.tableData)
                    let member = JSON.parse(JSON.stringify(this.clinical_content_top.member))
                    this.clinical_content_top = this.$refs.planList.datas
                    this.clinical_content_top.member = member
                    this.clinical_content_top.project_task = list
                }
                // this.clinical_content_top.project_task = [...this.$refs.planList.tableData]
                this.sortData(this.clinical_content_top.project_task | []);

                this.clinical_content_top.member_id = [];
                for (let i = 0; i < this.clinical_content_top.member.length; i++){
                    this.clinical_content_top.member_id.push(this.clinical_content_top.member[i].member_id)
                }

                this.datas = this.clinical_content_top;

                if (!this.projectValidate(this.datas)){
                    return;
                }

                await this.updataProject().then(()=>{
                    this.$api.PROJECT_MANAGER_PROJECT_STATUS(this.datas.id,5).then(res=>{
                        if (res.code == 200){
                            this.$message.success("成功")
                            // this.getData(this.datas.id)
                            this.$route.params.refresh = true;
                            this.$router.back()
                        }
                    }).catch(err=>{

                    })
                });
            },
            auditProject1:function(){
                this.$api.PROJECT_MANAGER_PROJECT_STATUS(this.datas.id,6).then(res=>{
                    if (res.code == 200){
                        this.$message.success("成功")
                        this.$router.back();
                    }
                }).catch(err=>{

                })
            },
            projectValidate:function(data){

                if (!data.member || data.member.length == 0){
                    //
                    this.$message({
                        message: '请添加项目组成员',
                        type: 'warning'
                    })
                    return false;
                }
                if (!data.project_template_id){
                    this.$message({
                        message: '请选择项目模板',
                        type: 'warning'
                    })
                    return false;
                }
                if (!data.plan_start_time){
                    this.$message({
                        message: '请选择项目开始时间',
                        type: 'warning'
                    })
                    return false;
                }
                if (!data.plan_end_time){
                    this.$message({
                        message: '请选择项目结束时间',
                        type: 'warning'
                    })
                    return false;
                }
                if (!data.duration){
                    this.$message({
                        message: '请设置项目工期',
                        type: 'warning'
                    })
                    return false;
                }

                if (!data.project_task || !data.project_task.length){
                    this.$message({
                        message: '请添加里程碑',
                        type: 'warning'
                    })
                    return false;
                }
                if (!this.checkTaskData(data.project_task,data.plan_start_time,data.plan_end_time)){
                    return false;
                }

                return true;
            },
            checkTaskData:function(list,s_time,e_time){
                for (let i = 0; i < list.length; i++){
                    let data = list[i];

                    if (!data.task_name){
                        this.$message({
                            message: '请添加任务名称',
                            type: 'warning'
                        })
                        return false;
                    }
                    if (!data.start_date){
                        this.$message({
                            message: "请设置" + data.task_name + "的起始时间",
                            type: 'warning'
                        })
                        return false;
                    }
                    if (!data.end_date){
                        this.$message({
                            message: "请设置" + data.task_name + "的结束时间",
                            type: 'warning'
                        })
                        return false;
                    }
                    if (!data.duration){
                        this.$message({
                            message: "请设置" + data.task_name + "的工期",
                            type: 'warning'
                        })
                        return false;
                    }
                    if (!data.person_in_charge || !data.person_in_charge.member_id){
                        this.$message({
                            message: "请设置" + data.task_name + "的负责人",
                            type: 'warning'
                        })
                        return false;
                    }
                    if (!data.task_member_id || !data.task_member_id.length){
                        this.$message({
                            message: "请设置" + data.task_name + "的参与人",
                            type: 'warning'
                        })
                        return false;
                    }

                    if (new Date(data.start_date.replace(/-/g,'/')).getTime() < new Date(s_time.replace(/-/g,'/')).getTime()){
                        this.$message({
                            message: '请调整' + data.task_name + "的开始日期",
                            type: 'warning'
                        })
                        return false;
                    }

                    if (new Date(data.end_date.replace(/-/g,'/')).getTime() > new Date(e_time.replace(/-/g,'/')).getTime()){
                        this.$message({
                            message: '请调整' + data.task_name + "的结束日期",
                            type: 'warning'
                        })
                        return false;
                    }

                    if (data.children && data.children.length){
                        if (!this.checkTaskData(data.children,data.start_date,data.end_date)){
                            return false;
                        }
                    }
                }

                return true;
            },
            sortData:function(list){
                let sort = 1;
                for (let i = 0; i < list.length; i++){
                    list[i].sort = sort;
                    sort++;
                    if (list[i].children && list[i].children.length > 0){
                        this.sortData(list[i].children);
                    }
                }
            },
            async confirmDataBack (data) {


                this.$api.PROJECT_START_PROJECT_UPDATE_BOOK(this.datas.id,{project_design_book:data}).then(res=>{
                    if (res.code == 200){
                        this.$message.success("成功")
                        this.$router.back();
                    }else{
                        this.$message.error(res.msg)
                    }
                }).catch(err=>{

                })

                // this.datas.project_design_book = data;
                // await this.updataProject();
                //
                // this.$api.PROJECT_MANAGER_PROJECT_STATUS(this.datas.id,2).then(res=>{
                //     if (res.code == 200){
                //         this.$message.success("成功")
                //         this.getData(this.datas.id)
                //     }else{
                //         this.$message.error(res.msg)
                //     }
                // }).catch(err=>{
                //
                // })
            },
            updataProject:function () {
                return new Promise((resolve, reject) => {
                    this.$api.PROJECT_MANAGER_PROJECT_UPDATA(this.datas.id,this.datas).then(res=>{
                        if (res.code == 200){
                            resolve()
                        }else {
                            reject(res.msg)
                        }
                    }).catch(err=>{
                        reject(err)
                    })
                })

            },
            automaticSave:function(){
                let list = this.initOldData(this.$refs.planList.tableData)
                let data = {...this.clinical_content_top}
                data.project_task = list
                data.member_id = [];
                for (let i = 0; i < data.member.length; i++){
                    data.member_id.push(data.member[i].member_id)
                }
                if (!data.duration){
                    data.duration = 0;
                }

                this.$api.PROJECT_MANAGER_PROJECT_UPDATA(this.datas.id,data).then(res=>{
                    if (res.code == 200){
                    }else {
                    }
                }).catch(err=>{
                })
            },
            saveClick :function() {

                let list = this.initOldData(this.$refs.planList.tableData)
                this.clinical_content_top.project_task = list
                this.clinical_content_top.member_id = [];
                for (let i = 0; i < this.clinical_content_top.member.length; i++){
                    this.clinical_content_top.member_id.push(this.clinical_content_top.member[i].member_id)
                }
                if (!this.clinical_content_top.duration){
                    this.clinical_content_top.duration = 0;
                }

                this.datas = {...this.clinical_content_top};

                this.updataProject().then(()=>{
                    this.$message.success("保存成功")
                    this.getData(this.datas.id);
                });

            },
            initOldData:function(list){
                let arr = []
                for (let i = 0; i < list.length; i++){
                    let data = {...list[i]}
                    data._all_children = null;
                    data._cycle = null;
                    data._identityId = null
                    data._isLeaf = null;
                    data._level = null;
                    data._oldEndDate = null;
                    data._oldStartDate = null;
                    data._parent = null;
                    data._parents = null;
                    if (list[i].children && list[i].children.length > 0){
                        let children = this.initOldData(list[i].children)
                        data.children = children;
                    }
                    if (data.level == 1){
                        data.task_type = "1"
                    }else{
                        data.task_type = (data.children && data.children.length) ? '2' : "3"
                    }
                    data.sort = i+1;
                    arr.push(data)
                }
                return arr;
            },
            aaaa:function(){
                this.$api.PROJECT_MANAGER_PROJECT_STATUS(this.datas.id,4).then(res=>{
                    if (res.code == 200){
                        this.$message.success("成功")
                        this.getData(this.datas.id)
                    }
                }).catch(err=>{

                })
            },
        },
    }
</script>

<style lang="scss" scoped>
  @import "../../../../assets/scss/views/projectManagement/list/edit.scss";
</style>
